package com.yanchangapp.widget;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.ExceptionHandle;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.DisplayHelper;
import com.yanchangapp.R;
import com.yanchangapp.base.HeadApiRetrofit;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.commom.MailType;
import com.yanchangapp.model.response.MailUnreadResponse;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MailListPopupWindow extends PopupWindow implements View.OnClickListener {
    private Context context;
    private View window;
    private Animation animationIn, animationOut;
    private boolean isDismiss = false;
    private LinearLayout id_ll_root;
    private LinearLayout mLlInbox,mLlDraft,mLlSent,mLlSpam,mLlTrash;
    private TextView mTvInbox,mTvDraft,mTvSent,mTvSpam,mTvTrash;
    private RedDotView mDotInBox,mDotSpam,mDotTrash;
    private ImageView mIvInbox,mIvDraft,mIvSent,mIvSpam,mIvTrash;
    private ImageView mArrowImage;
    private OnPopItemSelectedListener mOnPopItemSelectedListener;
    private MailType beforeMailType = MailType.INBOX;
    private MailType currentMailType = MailType.INBOX;
    public MailListPopupWindow(Context context) {
        super(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        this.context = context;
        window = LayoutInflater.from(context).inflate(R.layout.popup_mail_type_list, null);
        this.setContentView(window);
        this.setAnimationStyle(R.style.WindowStyle);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.update();
        this.setBackgroundDrawable(new ColorDrawable(Color.argb(123, 0, 0, 0)));
        /* 获得图片*/
        setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setClippingEnabled(false);

        animationIn = AnimationUtils.loadAnimation(context, R.anim.an_photo_album_show);
        animationOut = AnimationUtils.loadAnimation(context, R.anim.an_photo_album_dismiss);
        initView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llInbox:
                inboxSelected();
                break;
            case R.id.llDraft:
                draftSelected();
                break;
            case R.id.llSent:
                sentSelected();
                break;
            case R.id.llSpam:
                spamSelected();
                break;
            case R.id.llTrash:
                trashSelected();
                break;
                default:
                    break;
        }
    }
    
    private void inboxSelected(){
        currentMailType = MailType.INBOX;
        if (beforeMailType == currentMailType){
            dismiss();
            return;
        }
        setBeforeUnSelected();
        mTvInbox.setSelected(true);
        mIvInbox.setSelected(true);
        goBackNow();
        dismiss();
    }
    
    private void draftSelected(){
        currentMailType = MailType.DRAFT;
        if (beforeMailType == currentMailType){
            dismiss();
            return;
        }
        setBeforeUnSelected();
        mTvDraft.setSelected(true);
        mIvDraft.setSelected(true);
        goBackNow();
        dismiss();
    }
    
    private void sentSelected(){
        currentMailType = MailType.SENT;
        if (beforeMailType == currentMailType){
            dismiss();
            return;
        }
        setBeforeUnSelected();
        mTvSent.setSelected(true);
        mIvSent.setSelected(true);
        goBackNow();
        dismiss();
    }
    
    private void spamSelected(){
        currentMailType = MailType.SPAM;
        if (beforeMailType == currentMailType){
            dismiss();
            return;
        }
        setBeforeUnSelected();
        mTvSpam.setSelected(true);
        mIvSpam.setSelected(true);
        goBackNow();
        dismiss();
    }
    
    private void trashSelected(){
        currentMailType = MailType.TRASH;
        if (beforeMailType == currentMailType){
            dismiss();
            return;
        }
        setBeforeUnSelected();
        mTvTrash.setSelected(true);
        mIvTrash.setSelected(true);
        goBackNow();
        dismiss();
    }


    private void goBackNow(){
        beforeMailType = currentMailType;
        if (mOnPopItemSelectedListener != null){
            mOnPopItemSelectedListener.popItemSelected(currentMailType);
        }

    }

    private void setBeforeUnSelected(){
        switch (beforeMailType){
            case INBOX:
                mTvInbox.setSelected(false);
                mIvInbox.setSelected(false);
                break;
            case SPAM:
                mTvSpam.setSelected(false);
                mIvSpam.setSelected(false);
                break;
            case SENT:
                mTvSent.setSelected(false);
                mIvSent.setSelected(false);
                break;
            case DRAFT:
                mTvDraft.setSelected(false);
                mIvDraft.setSelected(false);
                break;
            case TRASH:
                mTvTrash.setSelected(false);
                mIvTrash.setSelected(false);
                break;
                default:
                    break;
        }
    }

    private void initView() {
        id_ll_root = (LinearLayout) window.findViewById(R.id.llPopRoot);
        id_ll_root.setOnClickListener(v -> MailListPopupWindow.this.dismiss());

        mLlInbox = id_ll_root.findViewById(R.id.llInbox);
        mLlDraft = id_ll_root.findViewById(R.id.llDraft);
        mLlSent = id_ll_root.findViewById(R.id.llSent);
        mLlSpam = id_ll_root.findViewById(R.id.llSpam);
        mLlTrash = id_ll_root.findViewById(R.id.llTrash);
        
        mLlInbox.setOnClickListener(this);
        mLlDraft.setOnClickListener(this);
        mLlSent.setOnClickListener(this);
        mLlSpam.setOnClickListener(this);
        mLlTrash.setOnClickListener(this);

        mTvInbox = id_ll_root.findViewById(R.id.tvInbox);
        mTvDraft = id_ll_root.findViewById(R.id.tvDraft);
        mTvSent = id_ll_root.findViewById(R.id.tvSent);
        mTvSpam = id_ll_root.findViewById(R.id.tvSpam);
        mTvTrash = id_ll_root.findViewById(R.id.tvTrash);

        mDotInBox = id_ll_root.findViewById(R.id.dotInbox);
        mDotSpam = id_ll_root.findViewById(R.id.dotSpam);
        mDotTrash = id_ll_root.findViewById(R.id.dotTrashNum);

        mIvInbox = id_ll_root.findViewById(R.id.ivInbox);
        mIvDraft = id_ll_root.findViewById(R.id.ivDraft);
        mIvSent = id_ll_root.findViewById(R.id.ivSent);
        mIvSpam = id_ll_root.findViewById(R.id.ivSpam);
        mIvTrash = id_ll_root.findViewById(R.id.ivTrash);

        // 默认初始化...
        mTvInbox.setSelected(true);
        mIvInbox.setSelected(true);
    }

    @Override
    public void showAsDropDown(View anchor) {
        try {
            if (Build.VERSION.SDK_INT >= 24) {
                Rect rect = new Rect();
                anchor.getGlobalVisibleRect(rect);
                // 如果有值的话 那么就小了呗
                // 适配全面屏....
                // 解决全面屏手机使用顶部弹窗带来的问题
                if (DisplayHelper.isNavigationBarExist((Activity) context)){
                    int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
                    setHeight(h);
                }else {
                    //全面屏手机需要获取真实高度....
                    int h = DisplayHelper.getRealScreenSize(context)[1] - rect.bottom;
                    setHeight(h);
                }
            }
            super.showAsDropDown(anchor);
            isDismiss = false;
            id_ll_root.startAnimation(animationIn);
            // 动画旋转....
            ObjectAnimator.ofFloat(mArrowImage, View.ROTATION.getName(), 180, 0).start();
            // todo 展示时进行网络请求获取对应的未读数量....
            queryUnreadCount();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 当进入页面的时候 获取未读取的邮件数量...
    private void queryUnreadCount(){
        HeadApiRetrofit.getInstance().getUnReadCount()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<MailUnreadResponse>() {
                    @Override
                    public void onNext(MailUnreadResponse mailUnreadResponse) {
                        if (mailUnreadResponse.getCode() == AppConstant.REQUEST_SUCCESS){
                            int inboxNum =  mailUnreadResponse.getData().getINBOX();
                            int spamNum =  mailUnreadResponse.getData().getSPAM();
                            int trashNum =  mailUnreadResponse.getData().getTRASH();
                            mDotInBox.setBadgeCount(inboxNum);
                            mDotSpam.setBadgeCount(spamNum);
                            mDotTrash.setBadgeCount(trashNum);
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {

                    }
                });
    }

    @Override
    public void dismiss() {
        if (isDismiss) {
            return;
        }
        ObjectAnimator.ofFloat(mArrowImage, View.ROTATION.getName(), -180, 0).start();
        isDismiss = true;
        id_ll_root.startAnimation(animationOut);
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isDismiss = false;
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
                    dismiss4Pop();
                } else {
                    MailListPopupWindow.super.dismiss();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 在android4.1.1和4.1.2版本关闭PopWindow
     */
    private void dismiss4Pop() {
        new Handler().post(MailListPopupWindow.super::dismiss);
    }

    public interface OnPopItemSelectedListener{
        void popItemSelected(MailType mailType);
    }

    public void setImageView(ImageView imageView) {
        this.mArrowImage = imageView;
    }

    public void setOnItemSelectedListener(OnPopItemSelectedListener onItemSelectedListener){
        this.mOnPopItemSelectedListener = onItemSelectedListener;
    }
}
